package cn.edu.ujn.lab2.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.edu.ujn.lab2.util.MyBatisUtils;
import cn.edu.ujn.lab2.dao.User;
import cn.edu.ujn.lab2.dao.UserMapper;
@Service("operationImpl")
public class OperationImpl implements Operation {

	@Autowired
	private UserMapper UserMapper;
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
	public User addUser(User User) {
		int insert = this.UserMapper.insert(User);
		return User;
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
	public boolean deleteUserByPrimaryKey(Integer id) {
		if ((UserMapper.deleteByPrimaryKey(id))==1) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
	public boolean updateUser(User User) {
		int updateByPrimaryKey = UserMapper.updateByPrimaryKey(User);
		if(updateByPrimaryKey==1) {
		return true;
		}else {
			return false;
		}
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
	public User findUserById(int id) {
		// TODO Auto-generated method stub
		User User = UserMapper.selectByPrimaryKey(id);
		return User;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
	public List<User> findAllUsers() {
		// TODO Auto-generated method stub
	 List<User> Users=UserMapper.selectAllUsers();
	return Users;
	}

	@Override
	public List<User> findOrdersbyUser(User user) {
		  // 1、通过工具类生成SqlSession对象
        SqlSession session = MyBatisUtils.getSession();
        // 2、查询id为1的用户信息
       List<User> users= session.selectList("cn.edu.ujn.lab2.dao.UserMapper.selectByPrimaryKey", user.getId());
        // 3、输出查询结果信息
       // System.out.println(users);
        // 4、关闭SqlSession
        session.close();
        return users;
	}

	@Override
	public List<User> findproductsbyordersOfUser(User user) {
		 // 1、通过工具类生成SqlSession对象
        SqlSession session = MyBatisUtils.getSession();
        // 2、查询id为1的用户信息
       List<User> users= session.selectList("cn.edu.ujn.lab2.dao.UserMapper.findByPrimaryKey", user.getId());
        // 3、输出查询结果信息
       // System.out.println(users);
        // 4、关闭SqlSession
        session.close();
        return users;
	}

}
